package com.axzhengxin.platform.afterloan.controller;

import com.axzhengxin.platform.afterloan.domain.RiskModelResult;
import com.axzhengxin.platform.afterloan.service.IRiskModelService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * RiskModelCallbackController
 * 预警模型回调API提供者
 *
 * @author jiangnan
 * @date 2021/3/17
 */
@Slf4j
@RestController
@RequestMapping(path = "/risk-warning")
public class RiskModelCallbackController {

    private IRiskModelService riskModelService;

    public RiskModelCallbackController(IRiskModelService riskModelService) {
        this.riskModelService = riskModelService;
    }

    @PostMapping(path = "/callback",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public RiskModelCallbackResponse callback(@RequestBody RiskModelCallbackRequest request) {
        try {
            riskModelService.handleCallback(request);
            return RiskModelCallbackResponse.ok();
        } catch (Throwable t) {
            log.error("写预警信息记录过程中发生异常", t);
            return RiskModelCallbackResponse.error();
        }
    }

    @Data
    public static class RiskModelCallbackRequest {

        private List<RiskModelResult> result;

    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class RiskModelCallbackResponse {

        private String code;

        private String message;

        static RiskModelCallbackResponse ok() {
            return new RiskModelCallbackResponse("200100", "");
        }

        static RiskModelCallbackResponse error() {
            return new RiskModelCallbackResponse("400100", "系统异常");
        }

    }

}
